package com.jlnk.stockdemo.viewmodel;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jlnk.stockdemo.bean.SpotListRequest;
import com.jlnk.stockdemo.bean.SpotListResponse;
import com.jlnk.stockdemo.callback.ResponseCallback;
import com.jlnk.stockdemo.utils.NetworkUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class SpotViewModel extends ViewModel {
    private static final String TAG = "SpotViewModel";
    private MutableLiveData<List<SpotListResponse.Data.Spot>> spotListLiveData;

    public SpotViewModel() {
        spotListLiveData = new MutableLiveData<>();
    }

    public LiveData<List<SpotListResponse.Data.Spot>> getSpotListLiveData() {
        return spotListLiveData;
    }

    // 获取现货列表
    public void fetchSpotList() {
        NetworkUtils.sendPostRequest(new SpotListRequest(), new ResponseCallback() {
            @Override
            public void onResponse(String response) {
                // 在这里处理响应数据
                Gson gson = new Gson();
                Type type = new TypeToken<SpotListResponse>(){}.getType();
                SpotListResponse spotListResponse = gson.fromJson(response, type);
                if (spotListResponse != null) {
                    // 在这里处理解析后的数据
                    List<SpotListResponse.Data.Spot> spotList = spotListResponse.getData().getSpotList();
                    spotListLiveData.postValue(spotList);
                }
            }

            @Override
            public void onPermissionError(String msg) {
                Log.d(TAG, "onPermissionError: " + msg);
            }

            @Override
            public void onInternalError(String msg) {
                Log.d(TAG, "onInternalError: " + msg);
            }

            @Override
            public void onFailure(IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
        });
    }
}
